package com.z1.core.io;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import com.z1.core.exception.Z1Exception;

public class ObjectByte {

	/**
	 * 对象转换为字节数组
	 * @param obj
	 * @return
	 */
	public static final byte[] toBytes(Object obj) {
		if (null == obj) { return null; }
		byte[] b = new byte[0];
		ByteArrayOutputStream out = null;
		ObjectOutputStream oout = null;
		try {
			out = new ByteArrayOutputStream();
			oout = new ObjectOutputStream(out);
			oout.writeObject(obj);
			b = out.toByteArray();
		}
		catch (Throwable e) {
			throw new Z1Exception(e);
		}
		finally {
			try {
				if (null != oout) { oout.close(); }
				if (null != out) { out.close(); }
			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}
		return b;
	}
	
	/**
	 * 字节数据转换为对象
	 * @param b
	 * @return
	 */
	public static final Object toObject(byte[] b) {
		if (null == b) { return null; }
		ByteArrayInputStream input = null;
		ObjectInputStream oinput = null;
		Object obj = null;
		try {
			input = new ByteArrayInputStream(b);
			oinput = new ObjectInputStream(input);
			obj = oinput.readObject();
		}
		catch (Throwable e) {
			throw new Z1Exception(e);
		}
		finally {
			try {
				if (null != oinput) { oinput.close(); }
				if (null != input) { input.close(); }
			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}
		return obj;
	}  

}
